package com.sx.netty.netty.demo01_GroupChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author ShuXin
 * @Description 群聊系统服务端，负责接受和转发客户端的消息
 * @Date 2020/11/18 9:37
 */

public class GroupChatServer {
    //    监听的端口
    private int port;

    public GroupChatServer(int port) {
        this.port = port;
    }

    //    编写run方法执行客户端请求
    public void run() throws InterruptedException {
//        创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
//        创建bootstrap
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //                        获取pipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //                        向pipeline中加入编解码器和channel
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });
            System.out.println("服务端已开启");
//        绑定端口
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
//        监听关闭端口
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer(8099).run();
    }

}
